package com.hqyj.bigdata.hiveproject.controller;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;

@Controller
@RequestMapping("commons")
public class CommonsController extends BaseController {

    @GetMapping("randomImgCode")
    //利用hutool工具类生成一个图形验证码
    public void generateRandomCodeImageByHutool(HttpServletRequest request, HttpServletResponse response,String token) {
        OutputStream out = null;
        try {
            //定义图形验证码的长、宽、验证码字符数、干扰元素个数
            LineCaptcha captcha = CaptchaUtil.createLineCaptcha(120, 45, 4, 20);
            //CircleCaptcha captcha = new CircleCaptcha(200, 100, 4, 20);
            //图形验证码写出，可以写出到文件，也可以写出到流
            //captcha.write("d:/circle.png");
            //验证图形验证码的有效性，返回boolean值
            //captcha.verify("1234");
            //获得生成的验证码
            String randomCode = captcha.getCode();
            //保存到redis缓存中
            redisUtil.set(token,randomCode,5); //五分钟之后验证码自动过期。

            //获得浏览器的输出流
            out = response.getOutputStream();
            captcha.write(out);
        } catch (Exception ex) {
            ex.printStackTrace();

        }finally{
            try{
                if(out!=null){
                    out.close();
                    out = null; //释放资源
                }
            }catch (Exception ex){
                ex.printStackTrace();
            }
        }
    }
}
